package controllers

import (
	"encoding/json"
	"volux/utils"

	"github.com/beego/beego/v2/server/web"
)

type ListenerController struct {
	web.Controller
}

type Listener struct {
	Address string `json:"address"`
	Port    int    `json:"port"`
	Type    string `json:"type"` // e.g., "tcp", "rdma"
}

func (c *ListenerController) AddListener() {
	nqn := c.Ctx.Input.Param(":nqn")
	if nqn == "" {
		utils.ErrorResponse(c.Controller, 400, "NQN is required")
		return
	}

	var listener Listener
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &listener); err != nil {
		utils.ErrorResponse(c.Controller, 400, "Invalid request body")
		return
	}

	spdkClient := utils.GetSPDKClient()
	if spdkClient == nil {
		utils.ErrorResponse(c.Controller, 500, "SPDK client not available")
		return
	}

	err := spdkClient.AddNVMFListener(nqn, listener.Type, listener.Address, uint16(listener.Port))
	if err != nil {
		utils.ErrorResponse(c.Controller, 500, "Failed to add listener: "+err.Error())
		return
	}

	utils.SuccessResponse(c.Controller, listener)
}

func (c *ListenerController) DeleteListener() {
	nqn := c.Ctx.Input.Param(":nqn")
	address := c.Ctx.Input.Param(":address")
	portStr := c.Ctx.Input.Param(":port")

	if nqn == "" || address == "" || portStr == "" {
		utils.ErrorResponse(c.Controller, 400, "NQN, address and port are required")
		return
	}

	spdkClient := utils.GetSPDKClient()
	if spdkClient == nil {
		utils.ErrorResponse(c.Controller, 500, "SPDK client not available")
		return
	}

	// 获取传输类型，假设从请求体获取
	var data struct {
		Type string `json:"type"`
	}
	if err := json.Unmarshal(c.Ctx.Input.RequestBody, &data); err != nil {
		utils.ErrorResponse(c.Controller, 400, "Invalid request body")
		return
	}

	err := spdkClient.RemoveListener(nqn, data.Type, "ipv4", address, portStr)
	if err != nil {
		utils.ErrorResponse(c.Controller, 500, "Failed to remove listener: "+err.Error())
		return
	}

	utils.SuccessResponse(c.Controller, map[string]string{
		"message": "Listener removed successfully",
	})
}

func (c *ListenerController) GetListeners() {
	nqn := c.Ctx.Input.Param(":nqn")
	if nqn == "" {
		utils.ErrorResponse(c.Controller, 400, "NQN is required")
		return
	}

	spdkClient := utils.GetSPDKClient()
	if spdkClient == nil {
		utils.ErrorResponse(c.Controller, 500, "SPDK client not available")
		return
	}

	listeners, err := spdkClient.GetListeners(nqn)
	if err != nil {
		utils.ErrorResponse(c.Controller, 500, "Failed to get listeners")
		return
	}

	utils.SuccessResponse(c.Controller, listeners)
}
